﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;

namespace MVCCentral.Framework.UrlHelpers
{
    public static class UrlHelperExtensions
    {
        public static string AppPath(this UrlHelper urlHelper, string relativePath)
        {
            if (relativePath == null) return null;

            return VirtualPathUtility.ToAbsolute(relativePath, urlHelper.RequestContext.HttpContext.Request.ApplicationPath);
        }



        #region SiteUrl

        /* Borrowed these methods from Rob Conery's Kona application
         */
        public static string GetSiteUrl(this UrlHelper helper)
        {
            var ctx = HttpContext.Current;//helper.RequestContext.HttpContext;
            string Port = ctx.Request.ServerVariables["SERVER_PORT"];
            if (Port == null || Port == "80" || Port == "443")
                Port = "";
            else
                Port = ":" + Port;

            string Protocol = ctx.Request.ServerVariables["SERVER_PORT_SECURE"];
            if (Protocol == null || Protocol == "0")
                Protocol = "http://";
            else
                Protocol = "https://";

            string appPath = ctx.Request.ApplicationPath;
            if (appPath == "/")
                appPath = "";

            string sOut = Protocol + ctx.Request.ServerVariables["SERVER_NAME"] + Port + appPath;
            return sOut;
        }
        public static string GetSiteUrl(this HttpContext context)
        {
            HttpContextWrapper wrapper = new HttpContextWrapper(context);
            return GetSiteUrl(wrapper as HttpContextBase, true);
        }
        public static string GetSiteUrl(HttpContextBase context, bool usePort)
        {
            string Port = context.Request.ServerVariables["SERVER_PORT"];
            if (usePort)
            {
                if (Port == null || Port == "80" || Port == "443")
                    Port = "";
                else
                    Port = ":" + Port;
            }
            string Protocol = context.Request.ServerVariables["SERVER_PORT_SECURE"];
            if (Protocol == null || Protocol == "0")
                Protocol = "http://";
            else
                Protocol = "https://";

            string appPath = context.Request.ApplicationPath;
            if (appPath == "/")
                appPath = "";

            string sOut = Protocol + context.Request.ServerVariables["SERVER_NAME"] + Port + appPath;
            return sOut;

        } 
        #endregion

    }
}
